package org.third.security.cert;

import org.junit.Test;

import java.security.KeyStore;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Enumeration;

public class CertificateTest {

    public static final String CERT_FILE = "tomcat1.cer";
    public static final String KEYSTORE_JKS = "tomcat.keystore";
    public static final String KEYSTORE_PKCS = "tomcatKeystore.p12";

    /**
     * <pre>
     //产生公私密钥对
     * keytool -genkey -alias testkeypair -keyalg RSA -keysize 1024 -sigalg MD5withRSA
     *  -dname "CN=Li, OU=InfosecLab, O=InfosecLab Group, L=Beijing, ST=Beijing, C=CN"
     *  
     * // 产生自签证书
     *  keytool -selfcert -alias testkeypair -dname "CN=Li, OU=InfosecLab, O=InfosecLab Group, L=Beijing, ST=Beijing, C=CN"
     *  
     *  //导出自签证书, 选项rfc是把证书输出为RFC1421定义的、用Base64最终编码的格式
     *  keytool -export -rfc -alias testkeypair -file mycert.crt
     * </pre>
     * 
     * @throws Exception
     */
    @Test
    public void readCertficate() throws Exception {

        CertificateFactory certificate_factory = CertificateFactory.getInstance("X.509");
        // FileInputStream file_inputstream = new
        // FileInputStream(CertificateTest.class.getResource(CERT_FILE).toString());
        X509Certificate x509certificate = (X509Certificate) certificate_factory
                .generateCertificate(CertificateTest.class.getResourceAsStream(CERT_FILE));
        printCertficate(x509certificate);

    }

    private static final void printKeystore(KeyStore keystore) {
        try {

            for (Enumeration<String> aliases = keystore.aliases(); aliases.hasMoreElements();) {
                printCertficate(keystore.getCertificate(aliases.nextElement()));
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    private static void printCertficate(Certificate certificate) {
        System.out.println(certificate.getType());
        PublicKey publicKey = certificate.getPublicKey();
        if (certificate instanceof X509Certificate) {
            X509Certificate x509Certificate = (X509Certificate) certificate;
            // String encodedString = new String(x509certificate.getEncoded());
            // System.out.println(encodedString);
            System.out.println(x509Certificate.getSigAlgName());
            System.out.println(x509Certificate.getSigAlgOID());
            System.out.println(x509Certificate.getSignature());
            System.out.println(x509Certificate.getVersion());
            System.out.println(x509Certificate.getSubjectDN());
//            System.out.println(x509Certificate.getSubjectAlternativeNames());
            String CA_ItemData[][] = new String[][] {                   //
                    { "类型", x509Certificate.getType() },                   //
                    { "版本", Integer.toString(x509Certificate.getVersion()) },                   //
                    { "标题", x509Certificate.getSubjectDN().getName() } };
            /*
             * 以下类似，这里省略 Field=x509certificate.getNotBefore().toString();得到开始有效日期 Field=x509certificate.
             * getNotAfter().toString();得到截止日期 Field=x509certificate.getSerialNumber().toString(16);得到序列号
             * Field=x509certificate.getIssuerDN().getName();得到发行者名 Field=x509certificate.getSigAlgName();得到签名算法
             * Field=x509certificate.getPublicKey().getAlgorithm();得到公钥算法
             */
            // file_inputstream.close();
        }
    }

    @Test
    public void testKeystoreWithJks() {
        KeyStore keystore;
        try {
            keystore = KeyStore.getInstance("JKS");
            keystore.load(CertificateTest.class.getResourceAsStream(KEYSTORE_JKS), "tomcat1".toCharArray());
            printKeystore(keystore);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    

    @Test
    public void testKeystoreWithPkcs() {
        KeyStore keystore;
        try {
            keystore = KeyStore.getInstance("jks","JsafeJCE");
            keystore.load(CertificateTest.class.getResourceAsStream(KEYSTORE_PKCS), "tomcat".toCharArray());
            System.out.println(keystore);
            System.out.println(keystore.getType());
            printKeystore(keystore);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    // private void testHpssoCertificate(X509Certificate x509certificate) throws HpSsoBaseException {
    // testHpssoCertificate(x509certificate);
    // SsoConfigurationManager ssoConfigurationManager = new XmlParserSsoConfigurationManager(
    // "C:/IDM/help/src/org/third/crypto/hpssoConfig.xml");
    // // init validators, add to ValidatorsInvoker list
    // // com.hp.ccue.identity.hpssoImpl.validators.clientCertificate.ClientCertificateValidator
    // ValidatorsInvoker validatorInvoker = ValidatorsInvoker.getInstance();
    // validatorInvoker.init(ssoConfigurationManager.getConfiguration());
    // HttpServletRequest httpServletRequest = null;
    // HttpServletResponse httpServletResponse = null;
    // validatorInvoker.runValidators(httpServletRequest, httpServletResponse);
    // }
}
